<template>
  <div class="plan-container">
    <div class="plan-header">
      <h2>计划管理</h2>
      <el-button type="primary" @click="showAddDialog">
        <el-icon><Plus /></el-icon> 新增计划
      </el-button>
    </div>

    <div class="calendar-container">
      <div class="calendar-header">
        <el-button-group>
          <el-button @click="prevMonth">
            <el-icon><ArrowLeft /></el-icon>
          </el-button>
          <el-button @click="nextMonth">
            <el-icon><ArrowRight /></el-icon>
          </el-button>
        </el-button-group>
        <span class="current-month">{{ currentMonthLabel }}</span>
      </div>
      <div class="calendar-week-header">
        <div v-for="day in weekDays" :key="day" class="week-day" :class="{ 'is-weekend': day === '日' || day === '六' }">
          {{ day }}
        </div>
      </div>
      <el-calendar v-model="currentDate" :locale="zhCn">
        <template #header="{ date }">
          <div class="calendar-header-content">
            <div class="calendar-title">{{ dayjs(date).format('YYYY年MM月') }}</div>
            <div class="calendar-actions">
              <el-button-group>
                <el-button size="small" @click="prevMonth">{{ calendarConfig.prevMonth }}</el-button>
                <el-button size="small" @click="currentDate = new Date()">{{ calendarConfig.today }}</el-button>
                <el-button size="small" @click="nextMonth">{{ calendarConfig.nextMonth }}</el-button>
              </el-button-group>
            </div>
          </div>
        </template>
        <template #default="{ date }">
          <div class="calendar-body">
            <div v-for="(week, weekIndex) in getCalendarDays(date)" :key="weekIndex" class="calendar-week">
              <div 
                v-for="day in week" 
                :key="day.date" 
                class="calendar-day"
                :class="{
                  'is-today': day.isToday,
                  'is-selected': day.isSelected,
                  'is-other-month': day.isOtherMonth,
                  'has-plans': getPlansForDate(day.fullDate).length > 0
                }"
                @dblclick="() => showDayPlans(day.fullDate)"
              >
                <span class="day-number">{{ day.day }}</span>
                <div class="plan-list" v-if="getPlansForDate(day.fullDate).length > 0">
                  <div 
                    v-for="plan in getPlansForDate(day.fullDate)" 
                    :key="plan.id"
                    class="plan-item"
                    :class="plan.timeType"
                    @click.stop="editPlan(plan)"
                  >
                    <span class="plan-title">{{ plan.name }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>
      </el-calendar>
    </div>

    <!-- 日期计划列表对话框 -->
    <el-dialog
      v-model="dayPlansVisible"
      :title="dayjs(selectedDate).format('YYYY年MM月DD日') + ' 的计划'"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
    >
      <div class="day-plans">
        <template v-if="selectedDayPlans.length > 0">
          <el-card v-for="plan in selectedDayPlans" :key="plan.id" class="plan-card">
            <div class="plan-card-header">
              <div class="plan-info">
                <h3>{{ plan.name }}</h3>
                <el-tag :type="getTimeTypeTag(plan.timeType)">{{ getTimeTypeLabel(plan.timeType) }}</el-tag>
              </div>
              <div class="plan-time">
                {{ formatTime(plan.time) }}
              </div>
            </div>
            <div class="plan-actions">
              <el-button type="primary" @click="editPlan(plan)" size="small">
                <el-icon><Edit /></el-icon> 编辑
              </el-button>
              <el-button type="danger" @click="handleDeletePlan(plan.id)" size="small">
                <el-icon><Delete /></el-icon> 删除
              </el-button>
            </div>
          </el-card>
        </template>
        <div v-else class="no-plans">
          <el-empty description="暂无计划" />
        </div>
        
        <!-- 添加新计划按钮 -->
        <div class="add-plan-button">
          <el-button type="primary" @click="addNewPlan(selectedDate)" size="small">
            <el-icon><Plus /></el-icon> 添加新计划
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 新增/编辑计划对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑计划' : '新增计划'" 
      width="500px"
    >
      <el-form :model="planForm" label-width="80px">
        <el-form-item label="计划名称" required>
          <el-input v-model="planForm.name" placeholder="请输入计划名称" />
        </el-form-item>
        <el-form-item label="日期" required>
          <el-date-picker
            v-model="planForm.date"
            type="date"
            placeholder="选择日期"
            :disabled-date="disabledDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="时间类型" required>
          <el-select v-model="planForm.timeType" placeholder="请选择时间类型" @change="handleTimeTypeChange">
            <el-option label="上午" value="morning" />
            <el-option label="中午" value="noon" />
            <el-option label="下午" value="afternoon" />
            <el-option label="晚上" value="evening" />
          </el-select>
        </el-form-item>
        <el-form-item label="具体时间" required>
          <el-time-picker
            v-model="planForm.time"
            :disabled-hours="getDisabledHours"
            :disabled-minutes="getDisabledMinutes"
            format="HH:mm"
            placeholder="请选择时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePlan">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Edit, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { getPlans, createPlan, updatePlan, deletePlan, updatePlanNotify } from '../api/plan'

// 设置 dayjs 语言为中文
dayjs.locale('zh-cn')

// 日历配置
const calendarConfig = {
  firstDayOfWeek: 1,
  monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  weekDays: ['日', '一', '二', '三', '四', '五', '六'],
  today: '今天',
  prevMonth: '上个月',
  nextMonth: '下个月'
}

// 计划列表
const plans = ref([])

// 获取计划列表
const fetchPlans = async () => {
  try {
    const res = await getPlans()
    if (res.success) {
      plans.value = res.data.map(plan => {
        const formattedPlan = {
          ...plan,
          timeType: plan.time_type,
          time: new Date(`2000-01-01T${plan.time}`),
          date: dayjs(plan.date).format('YYYY-MM-DD')
        }
        console.log('Formatted plan:', formattedPlan)
        return formattedPlan
      })
      console.log('All plans after fetch:', plans.value)
    }
  } catch (error) {
    console.error('获取计划列表失败:', error)
    ElMessage.error('获取计划列表失败')
  }
}

// 日历控制
const currentDate = ref(new Date())
const currentMonthLabel = computed(() => {
  return dayjs(currentDate.value).format('YYYY年MM月')
})

// 日期计划对话框控制
const dayPlansVisible = ref(false)
const selectedDate = ref('')
const selectedDayPlans = ref([])

// 对话框控制
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentPlanId = ref(null)
const planForm = reactive({
  name: '',
  date: '',
  timeType: '',
  time: null
})

// 禁用过去的日期
const disabledDate = (time) => {
  return dayjs(time).isBefore(dayjs(), 'day')
}

// 时间类型配置
const timeTypeConfig = {
  morning: { start: 6, end: 11, label: '上午' },
  noon: { start: 11, end: 14, label: '中午' },
  afternoon: { start: 14, end: 18, label: '下午' },
  evening: { start: 18, end: 23, label: '晚上' }
}

// 获取时间类型标签
const getTimeTypeLabel = (type) => {
  return timeTypeConfig[type]?.label || type
}

// 获取时间类型对应的标签类型
const getTimeTypeTag = (type) => {
  const tags = {
    morning: 'success',
    noon: 'warning',
    afternoon: 'info',
    evening: 'danger'
  }
  return tags[type] || 'info'
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 格式化完整时间
const formatFullTime = (date, time) => {
  if (!date || !time) return ''
  const timeStr = formatTime(time)
  return `${date} ${timeStr}`
}

// 处理时间类型变化
const handleTimeTypeChange = () => {
  planForm.time = null
}

// 获取禁用的小时
const getDisabledHours = () => {
  if (!planForm.timeType) return []
  const config = timeTypeConfig[planForm.timeType]
  const hours = []
  for (let i = 0; i < 24; i++) {
    if (i < config.start || i >= config.end) {
      hours.push(i)
    }
  }
  return hours
}

// 获取禁用的分钟
const getDisabledMinutes = (hour) => {
  if (!planForm.timeType) return []
  const config = timeTypeConfig[planForm.timeType]
  if (hour === config.start || hour === config.end - 1) {
    return []
  }
  return []
}

// 获取指定日期的计划
const getPlansForDate = (date) => {
  console.log('Getting plans for date:', date)
  console.log('Current plans:', plans.value)
  const plansForDate = plans.value.filter(plan => {
    const matches = plan.date === date
    console.log(`Plan ${plan.id} date: ${plan.date}, matches: ${matches}`)
    return matches
  })
  console.log('Found plans for date:', date, plansForDate)
  return plansForDate
}

// 显示日期计划
const showDayPlans = (date) => {
  console.log('Showing plans for date:', date) // 添加调试日志
  selectedDate.value = date
  selectedDayPlans.value = getPlansForDate(date)
  console.log('Selected plans:', selectedDayPlans.value) // 添加调试日志
  dayPlansVisible.value = true
  console.log('Dialog visible:', dayPlansVisible.value) // 添加调试日志
}

// 切换月份
const prevMonth = () => {
  currentDate.value = dayjs(currentDate.value).subtract(1, 'month').toDate()
}

const nextMonth = () => {
  currentDate.value = dayjs(currentDate.value).add(1, 'month').toDate()
}

// 显示新增对话框
const showAddDialog = () => {
  isEdit.value = false
  currentPlanId.value = null
  planForm.name = ''
  planForm.date = ''
  planForm.timeType = ''
  planForm.time = null
  dialogVisible.value = true
}

// 编辑计划
const editPlan = (plan) => {
  isEdit.value = true
  currentPlanId.value = plan.id
  planForm.name = plan.name
  planForm.date = plan.date
  planForm.timeType = plan.timeType
  planForm.time = plan.time
  dialogVisible.value = true
}

// 添加新计划
const addNewPlan = (date) => {
  isEdit.value = false
  currentPlanId.value = null
  planForm.name = ''
  planForm.date = date
  planForm.timeType = ''
  planForm.time = null
  dialogVisible.value = true
}

// 保存计划
const savePlan = async () => {
  if (!planForm.name || !planForm.date || !planForm.timeType || !planForm.time) {
    ElMessage.warning('请填写完整信息')
    return
  }

  try {
    const data = {
      name: planForm.name,
      // 将日期格式化为 MySQL DATE 格式 (YYYY-MM-DD)
      date: dayjs(planForm.date).format('YYYY-MM-DD'),
      timeType: planForm.timeType,
      time: dayjs(planForm.time).format('HH:mm:ss')
    }
    console.log('Saving plan data:', data)

    if (isEdit.value) {
      await updatePlan(currentPlanId.value, data)
      ElMessage.success('修改成功')
    } else {
      const res = await createPlan(data)
      console.log('Create plan response:', res)
      if (res.success) {
        ElMessage.success('添加成功')
      }
    }
    dialogVisible.value = false
    // 重新获取计划列表
    await fetchPlans()
  } catch (error) {
    console.error('保存计划失败:', error)
    ElMessage.error('保存计划失败')
  }
}

// 删除计划
const handleDeletePlan = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个计划吗？', '提示', {
      type: 'warning'
    })
    
    await deletePlan(id)
    plans.value = plans.value.filter(plan => plan.id !== id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除计划失败:', error)
      ElMessage.error('删除计划失败')
    }
  }
}

// 检查计划时间
const checkPlans = async () => {
  const now = new Date()
  const currentDate = dayjs(now).format('YYYY-MM-DD')
  const currentHour = now.getHours()
  const currentMinute = now.getMinutes()

  for (const plan of plans.value) {
    if (plan.notified) continue

    const planTime = new Date(plan.time)
    const planHour = planTime.getHours()
    const planMinute = planTime.getMinutes()

    if (currentDate === plan.date && 
        currentHour === planHour && 
        currentMinute === planMinute) {
      try {
        await updatePlanNotify(plan.id)
        ElMessage({
          message: `计划提醒：${plan.name}`,
          type: 'info',
          duration: 5000
        })
        plan.notified = true
      } catch (error) {
        console.error('更新计划提醒状态失败:', error)
      }
    }
  }
}

// 在组件挂载时获取计划列表
let timer = null

onMounted(async () => {
  await fetchPlans()
  timer = setInterval(checkPlans, 60000) // 每分钟检查一次
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})

// 星期几
const weekDays = ['日', '一', '二', '三', '四', '五', '六']

// 获取日历数据
const getCalendarDays = (date) => {
  const current = dayjs(date)
  const firstDay = current.startOf('month')
  const lastDay = current.endOf('month')
  
  // 获取当月第一天是星期几
  const firstDayWeek = firstDay.day()
  
  // 获取上个月需要显示的天数
  const prevMonthDays = firstDayWeek
  
  // 获取下个月需要显示的天数
  const nextMonthDays = 42 - (prevMonthDays + lastDay.date())
  
  const days = []
  let currentWeek = []
  
  // 添加上个月的日期
  for (let i = prevMonthDays - 1; i >= 0; i--) {
    const day = firstDay.subtract(i + 1, 'day')
    const fullDate = day.format('YYYY-MM-DD')
    currentWeek.push({
      day: day.date(),
      fullDate: fullDate,
      isOtherMonth: true,
      isToday: day.isSame(dayjs(), 'day'),
      isSelected: day.isSame(current, 'day')
    })
  }
  
  // 添加当月的日期
  for (let i = 1; i <= lastDay.date(); i++) {
    const day = current.date(i)
    const fullDate = day.format('YYYY-MM-DD')
    const dayPlans = getPlansForDate(fullDate)
    console.log(`Day ${fullDate} has ${dayPlans.length} plans`)
    currentWeek.push({
      day: i,
      fullDate: fullDate,
      isOtherMonth: false,
      isToday: day.isSame(dayjs(), 'day'),
      isSelected: day.isSame(current, 'day')
    })
    
    if (currentWeek.length === 7) {
      days.push(currentWeek)
      currentWeek = []
    }
  }
  
  // 添加下个月的日期
  for (let i = 1; i <= nextMonthDays; i++) {
    const day = lastDay.add(i, 'day')
    const fullDate = day.format('YYYY-MM-DD')
    currentWeek.push({
      day: day.date(),
      fullDate: fullDate,
      isOtherMonth: true,
      isToday: day.isSame(dayjs(), 'day'),
      isSelected: day.isSame(current, 'day')
    })
    
    if (currentWeek.length === 7) {
      days.push(currentWeek)
      currentWeek = []
    }
  }
  
  return days
}
</script>

<style scoped>
.plan-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 24px;
}

.plan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.plan-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.calendar-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.calendar-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
}

.current-month {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.calendar-cell {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 4px;
}

.date-number {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.plan-dots {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  justify-content: center;
}

.plan-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  cursor: pointer;
}

.plan-dot.morning {
  background-color: #67C23A;
}

.plan-dot.noon {
  background-color: #E6A23C;
}

.plan-dot.afternoon {
  background-color: #409EFF;
}

.plan-dot.evening {
  background-color: #F56C6C;
}

.day-plans {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 10px;
}

.plan-card {
  margin-bottom: 16px;
  transition: all 0.3s ease;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.plan-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.plan-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
}

.plan-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.plan-info h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.plan-time {
  font-size: 14px;
  color: #909399;
}

.plan-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 16px;
}

.el-form-item {
  margin-bottom: 20px;
}

:deep(.el-calendar-day) {
  height: 80px;
  padding: 4px;
}

:deep(.el-calendar__header) {
  padding: 12px 20px;
}

:deep(.el-calendar__body) {
  padding: 12px 20px 35px;
}

.calendar-header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  width: 100%;
}

.calendar-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.calendar-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

:deep(.el-calendar__header) {
  padding: 12px 0;
  width: 100%;
}

:deep(.el-calendar-table thead th) {
  font-weight: 500;
  color: #606266;
  padding: 8px;
  text-align: center;
}

:deep(.el-calendar-table thead th.is-weekend) {
  color: #F56C6C;
}

:deep(.el-calendar-table .el-calendar-day) {
  height: 80px;
  padding: 4px;
  box-sizing: border-box;
}

:deep(.el-calendar-table td) {
  border: none;
}

:deep(.el-calendar-table tr:first-child td) {
  border-top: none;
}

:deep(.el-calendar-table tr td:first-child) {
  border-left: none;
}

:deep(.el-calendar-table tr td:last-child) {
  border-right: none;
}

:deep(.el-calendar-table tr:last-child td) {
  border-bottom: none;
}

:deep(.el-calendar-table .el-calendar-day.is-selected) {
  background-color: #f0f9ff;
}

:deep(.el-calendar-table .el-calendar-day.is-today) {
  color: #409EFF;
  font-weight: bold;
}

.calendar-week-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  border-bottom: 1px solid #ebeef5;
  padding: 8px 0;
}

.week-day {
  font-weight: 500;
  color: #606266;
  padding: 8px;
}

.week-day.is-weekend {
  color: #F56C6C;
}

.calendar-body {
  padding: 12px;
}

.calendar-week {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  min-height: 80px;
}

.calendar-day {
  border: 1px solid #ebeef5;
  padding: 4px;
  min-height: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.calendar-day.is-today {
  color: #409EFF;
  font-weight: bold;
}

.calendar-day.is-selected {
  background-color: #f0f9ff;
}

.calendar-day.is-other-month {
  color: #c0c4cc;
}

.calendar-day.has-plans {
  background-color: #f0f9ff;
  border-color: #409EFF;
}

.calendar-day.has-plans .day-number {
  color: #409EFF;
  font-weight: bold;
}

.day-number {
  font-size: 14px;
  margin-bottom: 4px;
}

.add-plan-button {
  margin-top: 16px;
  text-align: center;
  padding: 16px;
  border-top: 1px solid #ebeef5;
}

.no-plans {
  padding: 40px 0;
  text-align: center;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-card__body) {
  padding: 0;
}

.plan-list {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 2px;
  margin-top: 4px;
  max-height: 60px;
  overflow-y: auto;
  padding: 0 2px;
}

.plan-item {
  padding: 2px 4px;
  border-radius: 2px;
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
  color: #fff;
  width: 100%;
  text-align: center;
}

.plan-item.morning {
  background-color: #67C23A;
}

.plan-item.noon {
  background-color: #E6A23C;
}

.plan-item.afternoon {
  background-color: #409EFF;
}

.plan-item.evening {
  background-color: #F56C6C;
}

.plan-title {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
}

.plan-item:hover {
  opacity: 0.8;
}
</style> 